package com.example.sangong.demo.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.example.sangong.http.Result;
import com.example.sangong.utils.WebSocketRelationUtils;
import com.example.sangong.websocket.WebSocketMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author websocket服务
 */
@ServerEndpoint(value = "/ws/{username}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    private static WebSocketRelationUtils webSocketRelationUtils;
    private static RestTemplate restTemplate;

    @PostConstruct
    public void init() {
        //是多例情况，手动初始化
        webSocketRelationUtils = SpringUtil.getBean(WebSocketRelationUtils.class);
        restTemplate = SpringUtil.getBean(RestTemplate.class);

    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        sessionMap.put(username, session);
        webSocketRelationUtils.addRelation(username);
        log.info("有新用户加入，username={}, 当前在线人数为：{}", username, sessionMap.size());

        WebSocketMessage result = new WebSocketMessage();
        List<String> userNames = new ArrayList<>();

        for (Object key : sessionMap.keySet()) {
            userNames.add(key.toString());
        }
        result.setSender("system");
        result.setContent("欢迎" + username + "加入进来！现在的用户有" + String.join(",", userNames));
        sendAllMessage(result);  // 后台发送消息给所有的客户端
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        sessionMap.remove(username);
        webSocketRelationUtils.removeRelation(username);
        log.info("有一连接关闭，移除username={}的用户session, 当前在线人数为：{}", username, sessionMap.size());
    }

    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
        log.info("服务端收到用户username={}的消息:{}", username, message);
        WebSocketMessage webSocketMessage = JSONUtil.toBean(message, WebSocketMessage.class);
        webSocketMessage.setSender(username);
        sendMessage(webSocketMessage);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    private void sendSingleMessage(WebSocketMessage message) {

        sendMsg(message, message.getTo(), null);

    }

    /**
     * 服务端发送消息给所有客户端
     */
    private void sendAllMessage(WebSocketMessage message) {

        try {
            Map<String, String> allRelation = webSocketRelationUtils.getAllRelation();
            Set<Map.Entry<String, String>> entries = allRelation.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                sendMsg(message, entry.getKey(), entry.getValue());
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    private void sendMsg(WebSocketMessage message, String userId, String url) {

        //需要重新构建新的消息对象，避免影响原来的消息
        WebSocketMessage msg = new WebSocketMessage();
        msg.setSender(message.getSender());
        msg.setContent(message.getContent());
        msg.setTo(userId);
        Session session = sessionMap.get(userId);
        if (Objects.nonNull(session)) {
            try {
                session.getBasicRemote().sendText(JSONUtil.toJsonStr(msg));
            } catch (IOException e) {
                log.error("websocket真实发送{}的消息异常了", msg, e);
                return;
            }
            log.info("服务端给客户端[{}]发送消息{}", session.getId(), msg);
        } else {
            if (StrUtil.isBlank(url)) {
                url = webSocketRelationUtils.getRelation(userId);
            }
            Result result = restTemplate.postForObject(url, msg, Result.class);
            log.info("远程调用发送websocket消息结果为：{}", result);
        }
    }

    /**
     * 服务端发送消息
     */
    public void sendMessage(WebSocketMessage message) {
        try {
            if (StrUtil.isBlank(message.getTo())) {
                sendAllMessage(message);
                return;
            }
            sendSingleMessage(message);

        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }
}
